const Controller = require('egg').Controller;
const use = (user) => {
  const uinfo = {
    id: user._id,
    username: user.username,
    realname: user.realname,
    mobile: user.mobile,
    email: user.email,
    avatars: user.avatarsPath,
    articles: user.articles,
    collect: user.collect,
    comments: user.comments,
    roles: user.roles,
    permission: user.permissions,
    menus: user.menus,
    date: user.date
  };
  return uinfo;
}

class ArticleController extends Controller {
  /**
   * 编辑文章
   * @permission 'article.v1.edit'
   */
	async article_edit() {
    const auth = this.ctx.session.user;
		const query = this.ctx.request.body,
          aid = query.id,  // 文章ID
          editObj = {
            author: query.author,
            title: query.title,
            summary: query.summary,
            content: query.content,
            banner: query.banner,
            label: query.label,
            isBanner: query.isBanner
          };
    console.log('39...', auth);
    // if(auth.roles != 7) {  // 超管可编辑修改任何文章
    //   if(query.author != auth.id) {  // 普通会员只能编辑修改自有文章
    //     this.ctx.status = 401;
    //     return this.ctx.body = {
    //       s: 0,
    //       m: `Fail~无权编辑此文章~`,
    //       d: {}
    //     };
    //   }
    // }
    if(aid) {  // Update this article if 'id' exist
      try {
        await this.ctx.service.article.article_update(aid, editObj);
        this.ctx.status = 200;
        return this.ctx.body = {
          s: 1,
          m: `ok~`,
          d: {}
        }
      }catch(err) {
        return this.ctx.body = {
          s: 0,
          m: `Fail~${err}`,
          d: {}
        }
      }
    }else {  // Add a new article
      try {
        const article = await this.ctx.service.article.article_add(editObj);
        const artObj = {
          user_id: article.author,
          label_id: article.label,
          article_id: article._id
        };
        this.ctx.service.label.add_article(artObj);  // 存入label集合
        this.ctx.service.user.add_article(artObj);  // 存入user集合

        this.ctx.status = 200;
        return this.ctx.body = {
            s: 1,
            m: 'ok~',
            d: {}
        };
      }catch(err) {
        return this.ctx.body = {
            s: 0,
            m: `Fail~${err}`,
            d: {}
        }  
      }
		}
	}
  // 查询文章列表
  async article_list() {
      const query = this.ctx.request.body,
          page = query.page,
          size = query.size;
      try{
          const list = await this.ctx.service.article.article_list(page, size);
          
          this.ctx.status = 200;
          return this.ctx.body = {
              s: 1,
              m: 'ok',
              d: {
                  total: list.length,
                  list,
              },
          };
      } catch(err) {
          return this.ctx.body = {
              s: 0,
              m: `fail~${err}`,
          }
      }
  }
  // 文章详情
  async article_detail() {
    const query = this.ctx.request.query,
          aid = query.id;
    try {
      const data = await this.ctx.service.article.article_det(aid);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 1,
        m: 'ok~',
        d: data
      }
    }catch(err) {
      return this.ctx.body = {
        s: 0,
        m: `fail~${err}`,
        d: {}
      }
    }
  }
  // 删除文章
  async article_del() {
    const query = this.ctx.request.body,
          auth = this.ctx.state.user;
          console.log('140...', query);
    const aid = query._id,
          uid = query.author.id,
          lid = query.label._id;
    try {
      if(uid == auth.id || auth.roles.value === 9) {
        await this.ctx.service.article.article_del(aid);  // 删除文章集合记录
        await this.ctx.service.user.del_article({uid, aid});  // 删除用户集合记录
        await this.ctx.service.label.del_article({lid, aid});  // 删除分类集合记录

        this.ctx.status = 200;
        return this.ctx.body = {
          s: 1,
          m: 'ok~',
          d: {}
        }
      }else {
        return this.ctx.body = {
          s: 0,
          m: `Fail~访问被拒绝~`,
          d: {}
        }
      }
    } catch(err) {
      return this.ctx.body = {
        s: 0,
        m: `fail~${err}`,
        d: {}
      };
    }
  }
  // 收藏文章
  /**
   * @params
   * { s: 200--收藏成功
   *   s: 202--取消收藏
   * }
   */
  async article_collect() {
    const query = this.ctx.request.body,
          auth = this.ctx.session.user;
    const aid = query.id,
          uid = auth._id,
          curUserCollect = auth.collect;
    // 检查接收到的文章ID是否存在于当前用户collect集合中
    try {
      console.log('186...', auth);
      const collected = JSON.stringify(curUserCollect).includes(aid);
      const data = await this.ctx.service.article.article_det(aid),
            collect = data.collect;
      if(collected) {
        const user = await this.ctx.service.member.cut_collect({uid, aid});  // 更新user collect集合
        await this.ctx.service.article.cut_collect(aid, collect);  // 更新article collect集合
        
        this.ctx.session.user = user;  // 更新用户session
        this.ctx.status = 200;
        return this.ctx.body = {
          s: 202,
          m: 'ok~cancel collect',
          d: {}
        };
      }else {
        const user = await this.ctx.service.member.add_collect({uid, aid});  // 更新user collect集合
        await this.ctx.service.article.add_collect(aid, collect);  // 更新article collect集合
        
        this.ctx.session.user = user;  // 更新用户session
        this.ctx.status = 200;
        return this.ctx.body = {
          s: 200,
          m: 'ok~collect success',
          d: {}
        }
      }
    }catch(err) {
      return this.ctx.body = {
        s: 500,
        m: `fail~${err}`,
        d: {}
      };
    }
  }
// cancel release
// exports.off = function(req, res) {
//   let articleId = req.params.id;
//   Article.unRelease(articleId, () => {
//     res.json({
//       s: 1,
//       m: 'ok',
//       d: {}
//     })
//   })
// }
}

module.exports = ArticleController;